package library.and.xps.com.step.view.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMapOptions;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.jude.utils.JUtils;

import java.util.ArrayList;
import java.util.List;

import library.and.xps.com.step.R;
import library.and.xps.com.step.SPConstant;
import library.and.xps.com.step.util.RunManager;
import library.and.xps.com.step.m.model.Coordinate;
import library.and.xps.com.step.m.model.Runlog;
import library.and.xps.com.step.util.MapUtils;


public class WorkoutFragment extends Fragment implements Handler.Callback {
    private final String TAG = getClass().getSimpleName();
    MapView mMapView;
    BaiduMap mBaiduMap;
    FrameLayout layout;
    LocationClient mLocationClient = null;
    BDLocationListener myListener = new MyLocationListener();
    Polyline mPolyline;
    Handler mHandler;
    final int DRAW_LINE = 0;
    final int INSERT_INTO_REALM = 1;
    Runlog mRunlog;
    Button toggle,toogleRun;
    MarkerOptions markerOptions;
    Marker startMarker;
    Marker currentMarker;
    boolean started;
    LinearLayout linearLayout;
    ScrollView scroll;
    TextView netWorkLocat;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mHandler = new Handler(Looper.getMainLooper(), this);
        View view = inflater.inflate(R.layout.fragment_workout, container, false);
        netWorkLocat = new TextView(getActivity());
        layout = (FrameLayout) view.findViewById(R.id.mvcontainer);
        toggle = (Button) view.findViewById(R.id.toggle_maptype);
        scroll = (ScrollView) view.findViewById(R.id.scroll);
        toogleRun = (Button) view.findViewById(R.id.toogleRun);
        linearLayout = (LinearLayout) view.findViewById(R.id.scroll_liner);
        toggle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBaiduMap.getMapType() == BaiduMap.MAP_TYPE_NORMAL) {
                    mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
                } else if (mBaiduMap.getMapType() == BaiduMap.MAP_TYPE_SATELLITE) {
                    mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
                }

            }
        });

        toogleRun.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(JUtils.getSharedPreference().getBoolean(SPConstant.APP_RUNNING,false)){
                    RunManager.getInstance().endRun();
                }else {
                    RunManager.getInstance().startRun();
                }
            }
        });

        mMapView = new MapView(getActivity(), new BaiduMapOptions());
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setTrafficEnabled(false);
        mLocationClient = new LocationClient(getActivity());
        mLocationClient.registerLocationListener(myListener);

        layout.addView(mMapView);
        markerOptions = new MarkerOptions();
        markerOptions.zIndex(20);
        markerOptions.animateType(MarkerOptions.MarkerAnimateType.grow);
        markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.currentpoint));
        mBaiduMap.getUiSettings().setCompassEnabled(false);
        mBaiduMap.getUiSettings().setOverlookingGesturesEnabled(false);
        mBaiduMap.setMyLocationEnabled(true);
        mBaiduMap.setViewPadding(35, 0, 20, 50);
        mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL, true, null));
        initLocation();
        mRunlog = new Runlog();

        return view;
    }

    //添加开始点marker
    void addStartMarker(LatLng latLng) {
        if (started) return;

        OverlayOptions markerOptions = new MarkerOptions().flat(true).anchor(0.5f, 0.5f)
                .zIndex(20)
                .animateType(MarkerOptions.MarkerAnimateType.grow)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.startpoint)).position(latLng);

        startMarker = (Marker) mBaiduMap.addOverlay(markerOptions);
        started = true;

    }

    //添加结束点marker
    void refreshEndMarker(LatLng latLng) {
        if (currentMarker != null && latLng != null) {
            currentMarker.setPosition(latLng);
        } else {
            markerOptions.position(latLng);
            currentMarker = (Marker) mBaiduMap.addOverlay(markerOptions);
        }
    }

    private void initLocation() {
        //定位方式要修改
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span = 1000 * 5;//定位一次
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps

        //可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setLocationNotify(false);
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        mLocationClient.setLocOption(option);
        mLocationClient.start();


    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case DRAW_LINE:
                drawLine();
                break;
            case INSERT_INTO_REALM:
                RunManager.getInstance().updateLog((BDLocation) msg.obj);
                break;
        }
        return false;
    }

    public void drawLine() {
        if (mRunlog.getmCoordinates().size() < 2) return;
        List<LatLng> polylines = new ArrayList<>();
        for (int index = 0; index < mRunlog.getmCoordinates().size(); index++) {
            Coordinate coordinate = mRunlog.getmCoordinates().get(index);
            LatLng latLng = new LatLng(coordinate.getLat(), coordinate.getLng());
            polylines.add(latLng);
        }

        ArrayList<Integer> colors = new ArrayList<>();
        for (Coordinate c : mRunlog.getmCoordinates()) {
            colors.add(c.getColorInSpeed());
        }

        PolylineOptions polylineOptions = new PolylineOptions().points(polylines).zIndex(10).width(10).colorsValues(colors);
        mPolyline = (Polyline) mBaiduMap.addOverlay(polylineOptions);

    }

    public class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(final BDLocation location) {
            JUtils.Log("WorkoutFragment", "locating..." + location.getRadius());

            if (location.getLocType() == BDLocation.TypeGpsLocation) {
                linearLayout.post(new Runnable() {
                    @Override
                        public void run() {

                        TextView textView = new TextView(getActivity());
                        textView.setTextSize(15);
                        StringBuilder stringBuilder = new StringBuilder();
                        stringBuilder.append("Radius:" + location.getRadius() + "\n");
                        if (location.getGpsAccuracyStatus() == BDLocation.GPS_ACCURACY_GOOD) {
                            stringBuilder.append("GpsAccuracyStatus:" + location.getGpsAccuracyStatus() + "GOOD");
                        } else if (location.getGpsAccuracyStatus() == BDLocation.GPS_ACCURACY_MID) {
                            stringBuilder.append("GpsAccuracyStatus:" + location.getGpsAccuracyStatus() + "MID");
                        } else if (location.getGpsAccuracyStatus() == BDLocation.GPS_ACCURACY_BAD) {
                            stringBuilder.append("GpsAccuracyStatus:" + location.getGpsAccuracyStatus() + "BAD");
                        } else if (location.getGpsAccuracyStatus() == BDLocation.GPS_ACCURACY_UNKNOWN) {
                            stringBuilder.append("GpsAccuracyStatus:" + location.getGpsAccuracyStatus() + "UNKNOWN");
                        }

                        stringBuilder.append("getSpeed:" + location.getSpeed() + "km/h" + "\n");
                        textView.setText(stringBuilder.toString());
                        textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
                        linearLayout.addView(textView);

                    }
                });
            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
                linearLayout.post(new Runnable() {
                    @Override
                    public void run() {
                        TextView textView = new TextView(getActivity());
                        StringBuilder sb = new StringBuilder();
                        // 网络定位结果
                        sb.append("\naddr : ");
                        sb.append(location.getAddrStr());    //获取地址信息

                        sb.append("\noperationers : ");
                        sb.append(location.getOperators());    //获取运营商信息

                        sb.append("\ndescribe : ");
                        sb.append("网络定位成功");

                        textView.setText("网络定位成功");
                        textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
                        linearLayout.addView(textView);
                    }
                });
            }

            //----------------------------------------------------------------------------
            LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
            addStartMarker(latLng);
            refreshEndMarker(latLng);

//            MyLocationData locData = new MyLocationData.Builder()
//                    .accuracy(5)
//                    .direction(location.getDirection())
//                    .latitude(latLng.latitude)
//                    .longitude(latLng.longitude).build();

            //mBaiduMap.setMyLocationData(locData);

            MapUtils.moveCameraTo(latLng, mBaiduMap);

            mRunlog.insertCoord(location);
            mHandler.sendEmptyMessage(DRAW_LINE);

            scroll.smoothScrollTo(0, linearLayout.getMeasuredHeight() + 100);

            Message msg = Message.obtain();
            msg.what = INSERT_INTO_REALM;
            msg.obj = location;


            mHandler.sendMessage(msg);
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

}
